import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import {
  Container,
  Grid,
  Card,
  CardContent,
  CardMedia,
  Typography,
  Box,
  Chip,
  Rating,
  TextField,
  InputAdornment,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Dialog,
  DialogTitle,
  DialogContent,
  Button,
  Paper,
  CardActionArea,
  Pagination,
  List,
  ListItem,
  ListItemText,
  Divider,
} from '@mui/material';
import { Search as SearchIcon, CloudUpload as CloudUploadIcon, TrendingUp as TrendingUpIcon } from '@mui/icons-material';
import UploadResource from '../features/resources/components/UploadResource';
import { ResourceService, Resource as ResourceType } from '../features/resources/services/ResourceService';
import { CircularProgress, Alert } from '@mui/material';

// 格式化文件大小的辅助函数
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
};

// 使用模拟数据的资源接口
interface MockResource {
  id: number;
  title: string;
  type: string;
  cover: string;
  size: string;
  downloads: number;
  rating: number;
  tags: string[];
}

interface Promotion {
  id: number;
  title: string;
  description: string;
  imageUrl: string;
  endDate: string;
}

// 热点数据接口
interface HotTopic {
  id: string;
  title: string;
  url?: string;
}

const mockPromotions: Promotion[] = [
  {
    id: 1,
    title: '周一免费下载',
    description: '每周一所有资源免费下载，快来参与！',
    imageUrl: '/covers/promotion_monday.jpg',
    endDate: '2024-01-15',
  },
  {
    id: 2,
    title: 'Taylor新专辑首发',
    description: '抢先收听Taylor Swift全新专辑！',
    imageUrl: '/covers/Taylor.png',
    endDate: '2024-01-20',
  },
  {
    id: 3,
    title: 'Adobe全系列特惠',
    description: 'Adobe软件合集，限时优惠中',
    imageUrl: '/covers/photoshop_cover_1.jpg',
    endDate: '2024-01-25',
  },
];

const mockResources: Resource[] = [
  {
    id: 1,
    title: '流浪地球2 4K蓝光原盘',
    type: '电影',
    cover: 'https://via.placeholder.com/300x400',
    size: '58.2GB',
    downloads: 15420,
    rating: 4.8,
    tags: ['科幻', '动作', '4K', 'HDR'],
  },
  {
    id: 2,
    title: 'Adobe Photoshop 2024',
    type: '软件',
    cover: 'https://via.placeholder.com/300x400',
    size: '3.8GB',
    downloads: 8956,
    rating: 4.5,
    tags: ['设计', '图像处理', 'Windows'],
  },
  {
    id: 3,
    title: 'Taylor Swift - 1989 (Taylor\'s Version)',
    type: '音乐',
    cover: 'https://via.placeholder.com/300x400',
    size: '1.2GB',
    downloads: 12568,
    rating: 4.9,
    tags: ['流行', 'FLAC', '2023'],
  },
  {
    id: 4,
    title: '赛博朋克2077',
    type: '游戏',
    cover: 'https://via.placeholder.com/300x400',
    size: '72.5GB',
    downloads: 25689,
    rating: 4.7,
    tags: ['RPG', '开放世界', 'Steam'],
  },
  {
    id: 5,
    title: '2024考研数学全程班',
    type: '教育',
    cover: 'https://via.placeholder.com/300x400',
    size: '15.8GB',
    downloads: 3567,
    rating: 4.9,
    tags: ['考研', '数学', '视频课程'],
  },
];

// 标签接口定义
interface Tag {
  id: string;
  name: string;
}

const sortOptions = ['最新发布', '最多下载', '最高评分', '最多收藏'];

const Resources = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedTagId, setSelectedTagId] = useState<string>('');
  const [tags, setTags] = useState<Tag[]>([]);
  const [loadingTags, setLoadingTags] = useState(false);
  const [sortBy, setSortBy] = useState('最新发布');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedResource, setSelectedResource] = useState<MockResource | null>(null);
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
  
  // 推荐资源状态
  const [recommendedResources, setRecommendedResources] = useState<ResourceType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(9); // 设置每页显示9个资源

  // 热点数据状态
  const [hotTopics, setHotTopics] = useState<HotTopic[]>([]);
  const [loadingHotTopics, setLoadingHotTopics] = useState(false);
  const [hotTopicsError, setHotTopicsError] = useState<string | null>(null);

  // 获取标签列表
  useEffect(() => {
    const fetchTags = async () => {
      try {
        setLoadingTags(true);
        const tagsData = await ResourceService.getTags();
        console.log('获取到的标签数据:', tagsData);
        // 确保tagsData是数组
        if (Array.isArray(tagsData)) {
          setTags(tagsData);
        } else {
          console.error('标签数据不是数组:', tagsData);
          setTags([]);
        }
      } catch (err) {
        console.error('获取标签列表失败:', err);
      } finally {
        setLoadingTags(false);
      }
    };

    fetchTags();
  }, []);

  // 获取资源列表
  useEffect(() => {
    const fetchResources = async () => {
      try {
        setLoading(true);
        setError(null);
        
        let response;
        if (selectedTagId) {
          // 如果选择了标签，则根据标签获取资源
          console.log('选中的标签ID:', selectedTagId);
          response = await ResourceService.getResourcesByTag(selectedTagId, page, pageSize);
        } else {
          // 否则获取所有资源
          response = await ResourceService.getResourceList(page, pageSize);
        }
        
        console.log('获取到的资源列表:', response);
        setRecommendedResources(response.records || []);
        setTotalPages(Math.ceil(response.total / pageSize));
      } catch (err) {
        console.error('获取资源列表失败:', err);
        setError(err instanceof Error ? err.message : '获取资源列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchResources();
  }, [page, pageSize, selectedTagId]);

  const handleResourceClick = (resource: MockResource) => {
    setSelectedResource(resource);
  };

  const handleClose = () => {
    setSelectedResource(null);
  };

  const handleUploadDialogOpen = () => {
    setUploadDialogOpen(true);
  };

  const handleUploadDialogClose = () => {
    setUploadDialogOpen(false);
  };

  // 获取今日热点数据
  useEffect(() => {
    const fetchHotTopics = async () => {
      try {
        setLoadingHotTopics(true);
        setHotTopicsError(null);
        
        const response = await fetch('/feishu-api/open-apis/bitable/v1/apps/VLqfbHkGmabwkpsyNV1cqqp6n2x/tables/tblJKk1HU8xbEPOz/records/search?page_size=20', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({})
        });

        if (!response.ok) {
          throw new Error(`获取热点数据失败: ${response.status}`);
        }

        const data = await response.json();
        console.log('获取到的热点数据:', data);
        
        // 假设返回的数据结构中包含热点列表
        // 根据实际API返回的数据结构进行调整
        if (data && data.data && data.data.items) {
          const topics = data.data.items.map((item: any) => ({
            id: item.record_id,
            title: item.fields.热点描述[0]?.text || '未知热点',
            url: item.fields.url || '#'
          })).slice(0, 10); // 只取前10个热点
          
          setHotTopics(topics);
        } else {
          // 如果API返回格式不符合预期，使用模拟数据
          const mockHotTopics: HotTopic[] = [
            { id: '1', title: '最新电影《沙丘2》4K资源已上线' },
            { id: '2', title: '2024年高考复习资料合集' },
            { id: '3', title: '热门游戏《艾尔登法环》DLC发布' },
            { id: '4', title: '新版Office 2024功能详解' },
            { id: '5', title: '最新前端开发技术学习资料' },
            { id: '6', title: '热门综艺《奔跑吧》最新一季' },
            { id: '7', title: '2024年考研英语词汇大全' },
            { id: '8', title: '最新版Photoshop教程' },
            { id: '9', title: '热门音乐专辑打包下载' },
            { id: '10', title: '最新科幻小说合集' },
          ];
          setHotTopics(mockHotTopics);
        }
      } catch (err) {
        console.error('获取热点数据失败:', err);
        setHotTopicsError(err instanceof Error ? err.message : '获取热点数据失败');
        
        // 使用模拟数据作为备选
        const mockHotTopics: HotTopic[] = [
          { id: '1', title: '最新电影《沙丘2》4K资源已上线' },
          { id: '2', title: '2024年高考复习资料合集' },
          { id: '3', title: '热门游戏《艾尔登法环》DLC发布' },
          { id: '4', title: '新版Office 2024功能详解' },
          { id: '5', title: '最新前端开发技术学习资料' },
          { id: '6', title: '热门综艺《奔跑吧》最新一季' },
          { id: '7', title: '2024年考研英语词汇大全' },
          { id: '8', title: '最新版Photoshop教程' },
          { id: '9', title: '热门音乐专辑打包下载' },
          { id: '10', title: '最新科幻小说合集' },
        ];
        setHotTopics(mockHotTopics);
      } finally {
        setLoadingHotTopics(false);
      }
    };

    fetchHotTopics();
  }, []);

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      {location.pathname === '/resources' ? (
        <>
          {/* 搜索和筛选区 */}
      <Box sx={{ mb: 4 }}>
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              placeholder="搜索资源..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          <Grid item xs={6} md={2}>
            <FormControl fullWidth>
              <InputLabel>标签</InputLabel>
              <Select
                value={selectedTagId}
                label="标签"
                onChange={(e) => setSelectedTagId(e.target.value)}
                disabled={loadingTags}
              >
                <MenuItem value="">全部</MenuItem>
                {tags.map((tag) => (
                  <MenuItem key={tag.id} value={tag.id}>{tag.name}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={6} md={2}>
            <FormControl fullWidth>
              <InputLabel>排序</InputLabel>
              <Select
                value={sortBy}
                label="排序"
                onChange={(e) => setSortBy(e.target.value)}
              >
                {sortOptions.map((option) => (
                  <MenuItem key={option} value={option}>{option}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={2}>
            <Button
              fullWidth
              variant="contained"
              startIcon={<CloudUploadIcon />}
              onClick={handleUploadDialogOpen}
              sx={{ height: '56px' }}
            >
              上传资源
            </Button>
          </Grid>
        </Grid>
      </Box>

      <Grid container spacing={3}>
        {/* 资源列表 */}
        <Grid item xs={12} md={9}>
          {/* 所有资源区域 */}
          <Typography variant="h6" gutterBottom>
            所有资源
          </Typography>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <CircularProgress />
            </Box>
          ) : error ? (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          ) : recommendedResources.length === 0 ? (
            <Alert severity="info" sx={{ mb: 2 }}>
              暂无资源
            </Alert>
          ) : (
            <Grid container spacing={3}>
              {recommendedResources.map((resource) => (
              <Grid item xs={12} sm={6} md={4} key={resource.id}>
                <Card sx={{
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                    cursor: 'pointer',
                    transition: 'all 0.3s ease',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: 6,
                    },
                  }}>
                  <CardActionArea onClick={() => navigate(`/resources/${resource.id}`)}>
                    <CardMedia
                      component="img"
                      height="250"
                      image={resource.coverImageUrl || resource.coverUrl || 'https://via.placeholder.com/300x400'}
                      alt={resource.title}
                    />
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography gutterBottom variant="h6" component="div" noWrap>
                      {resource.title}
                    </Typography>
                    <Box sx={{ mb: 1 }}>
                      {resource.tags && resource.tags.map((tag: string) => (
                        <Chip
                          key={tag}
                          label={tag}
                          size="small"
                          sx={{ mr: 0.5, mb: 0.5 }}
                        />
                      ))}
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                      {typeof resource.rating === 'number' && (
                        <>
                          <Rating value={resource.rating} precision={0.1} readOnly size="small" />
                          <Typography variant="body2" color="text.secondary" sx={{ ml: 1 }}>
                            {resource.rating}
                          </Typography>
                        </>
                      )}
                    </Box>
                    <Typography variant="body2" color="text.secondary">
                      上传者：{resource.uploaderName || '未知'}
                    </Typography>
                  </CardContent>
                </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
          )}
          
          {/* 添加分页组件 */}
          {!loading && !error && recommendedResources.length > 0 && totalPages > 1 && (
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
              <Pagination
                count={totalPages}
                page={page}
                onChange={(_, value) => setPage(value)}
                color="primary"
              />
            </Box>
          )}
        </Grid>

        {/* 右侧边栏 */}
        <Grid item xs={12} md={3}>
          {/* 今日热点模块 */}
          <Paper sx={{ mb: 3, overflow: 'hidden' }}>
            <Box sx={{ p: 2, bgcolor: 'primary.main', color: 'white', display: 'flex', alignItems: 'center' }}>
              <TrendingUpIcon sx={{ mr: 1 }} />
              <Typography variant="h6">不知道上传什么？今日热点在这里：</Typography>
            </Box>
            <List sx={{ p: 0 }}>
              {loadingHotTopics ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', p: 2 }}>
                  <CircularProgress size={24} />
                </Box>
              ) : hotTopicsError ? (
                <ListItem>
                  <ListItemText primary={`获取热点失败: ${hotTopicsError}`} />
                </ListItem>
              ) : (
                hotTopics.map((topic, index) => (
                  <React.Fragment key={topic.id}>
                    <ListItem 
                      button 
                      onClick={() => topic.url ? window.open(topic.url, '_blank') : null}
                      sx={{
                        '&:hover': {
                          bgcolor: 'action.hover',
                        },
                      }}
                    >
                      <ListItemText 
                        primary={
                          <Box sx={{ display: 'flex', alignItems: 'center' }}>
                            <Typography 
                              variant="body2" 
                              component="span" 
                              sx={{ 
                                mr: 1, 
                                color: 'primary.main', 
                                fontWeight: 'bold',
                                minWidth: '20px'
                              }}
                            >
                              {index + 1}.
                            </Typography>
                            <Typography variant="body2" noWrap>
                              {topic.title}
                            </Typography>
                          </Box>
                        } 
                      />
                    </ListItem>
                    {index < hotTopics.length - 1 && <Divider />}
                  </React.Fragment>
                ))
              )}
            </List>
          </Paper>

          {/* 促销活动列表 */}
          <Typography variant="h6" gutterBottom>
            促销活动
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {mockPromotions.map((promotion) => (
              <Paper
                key={promotion.id}
                onClick={() => navigate(`/resources/promotion/${promotion.id}`)}
                sx={{
                  overflow: 'hidden',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease',
                  '&:hover': {
                    transform: 'translateY(-4px)',
                    boxShadow: 3,
                  },
                }}
              >
                <CardMedia
                  component="img"
                  height="140"
                  image={promotion.imageUrl}
                  alt={promotion.title}
                />
                <Box sx={{ p: 2 }}>
                  <Typography variant="h6" gutterBottom>
                    {promotion.title}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" paragraph>
                    {promotion.description}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    截止日期：{promotion.endDate}
                  </Typography>
                </Box>
              </Paper>
            ))}
          </Box>
        </Grid>
      </Grid>

      {/* 资源详情对话框 */}
      <Dialog
        open={!!selectedResource}
        onClose={handleClose}
        maxWidth="md"
        fullWidth
      >
        {selectedResource && (
          <>
            <DialogTitle>{selectedResource.title}</DialogTitle>
            <DialogContent>
              <Box sx={{ display: 'flex', mb: 2 }}>
                <Box sx={{ flexShrink: 0, mr: 2 }}>
                  <img
                    src={selectedResource.cover}
                    alt={selectedResource.title}
                    style={{ width: 200, height: 'auto' }}
                  />
                </Box>
                <Box>
                  <Typography variant="h6" gutterBottom>
                    基本信息
                  </Typography>
                  <Typography variant="body1" paragraph>
                    类型：{selectedResource.type}
                  </Typography>
                  <Typography variant="body1" paragraph>
                    大小：{selectedResource.size}
                  </Typography>
                  <Typography variant="body1" paragraph>
                    下载次数：{selectedResource.downloads}
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                    <Typography variant="body1" sx={{ mr: 1 }}>
                      评分：
                    </Typography>
                    <Rating
                      value={selectedResource.rating}
                      precision={0.1}
                      readOnly
                    />
                    <Typography variant="body1" sx={{ ml: 1 }}>
                      ({selectedResource.rating})
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="body1" sx={{ mb: 1 }}>
                      标签：
                    </Typography>
                    {selectedResource.tags.map((tag) => (
                      <Chip
                        key={tag}
                        label={tag}
                        sx={{ mr: 0.5, mb: 0.5 }}
                      />
                    ))}
                  </Box>
                </Box>
              </Box>
            </DialogContent>
          </>
        )}
      </Dialog>

      {/* 上传资源对话框 */}
      <UploadResource
        open={uploadDialogOpen}
        onClose={handleUploadDialogClose}
      />
        </>
      ) : (
        <Outlet />
      )}
    </Container>
  );
};

export default Resources;